package com.yun.datastructure.map.hashmap.leetcode;

import java.util.*;

public class Leetcode819 {
    public String mostCommonWord1(String paragraph, String[] banned) {
        HashMap<String, Integer> map = new HashMap<>();
        String[] split = paragraph.toLowerCase().split("[^a-z]+");
        Set<String> set = Set.of(banned);
        for (String key : split) {
            if (!set.contains(key)) {
                map.compute(key, (k, v) -> v == null ? 1 : v + 1);
            }
        }
        maxValueHolder mv = new maxValueHolder(null, 0);
        map.forEach((key, value) -> {
            if (mv.value < value) {
                mv.key = key;
                mv.value = value;
            }
        });
        return mv.key;
    }

    static class maxValueHolder {
        String key;
        int value;

        public maxValueHolder(String key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    public String mostCommonWord(String paragraph, String[] banned) {
        HashMap<String, Integer> map = new HashMap<>();
        Set<String> set = Set.of(banned);
        char[] chars = paragraph.toLowerCase().toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char ch : chars) {
            if ('a' <= ch && ch <= 'z') {
                sb.append(ch);
            } else {
                if (sb.length() != 0) {
                    String key = sb.toString();
                    if (!set.contains(key)) {
                        map.compute(key, (k, v) -> v == null ? 1 : v + 1);
                    }
                    sb.setLength(0);
                }
            }
        }
        if (sb.length() > 0) {
            String key = sb.toString();
            if (!set.contains(key)) {
                map.compute(key, (k, v) -> v == null ? 1 : v + 1);
            }
        }
        int max = 0;
        String maxKey = null;
        for (Map.Entry<String, Integer> e : map.entrySet()) {
            Integer value = e.getValue();
            if (value > max) {
                max = value;
                maxKey = e.getKey();
            }
        }
        return maxKey;
    }

    public static void main(String[] args) {
        Leetcode819 e08 = new Leetcode819();
        String paragraph = "Bob. hIt, baLl";
        String[] banner = new String[]{"bob", "hit"};
        System.out.println(e08.mostCommonWord(paragraph, banner));
    }
}
